package com.common.www.controller.auth;


import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.base.jpa.domain.PageableRequest;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.Sort;
import com.common.www.bean.entity.auth.Dict;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.auth.DictService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.SortUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin()
@Api(tags = "字典相关接口")
@RequestMapping(value = {"/mgt/dict/"})

public class DictController extends DefaultCrudController<Dict, Long> {
    @Autowired
    private DictService service;

    @Override
    protected IBaseService getService() {
        return service;
    }

    @PostMapping(value="/get/{key}")
    public Result getDictListAll(@PathVariable("key") String key) {
        Map map = new HashMap<>();
        map.put("keyDict",key);
        map.put("level",1);

        PageableRequest request = new PageableRequest();
        request.setSort(SortUtils.addSort(new Sort("id", "asc")));
        List<Dict> result = service.queryDistinctToList(map,request);
        if(result.size()>0){
            return R.ok(result.get(0));
        }
        return R.fail("未找到相应数据");
    }

    @ApiOperation("保存字典的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveDict", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        Dict dict = JSONObject.parseObject(json,Dict.class);
        if(StringUtils.isEmpty(dict.getKeyDict())){
            return R.fail(NetCode.CODE_INPUT_OMIT);
        }
        Map param= new HashMap<>();
        param.put("keyDict",dict.getKeyDict());
        if(dict.getId()==null){
        }else {
            param.put("id_ne",dict.getId());
        }
        if(dict.getLevel()==2){
            param.put("valueDict",dict.getValueDict());
            param.put("level",2);
        }else{
            param.put("level",1);

        }
        if(service.queryDistinctToList(param,null).size()>0){
            return R.fail("数据已存在");
        }

        return R.ok(service.save(dict));
    }

    @ApiOperation(value = "逻辑删除批量", notes = "参数为JSON数据对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "8,28", dataType = "long", paramType = "query"),
    })
    @RequestMapping(value = "/deletesByLogic", method = RequestMethod.POST)
    public Result deletesByLogic(Long[] ids) {
        service.delete(ids);
        return R.ok();
    }


    @ApiOperation("批量更新顺序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "originId", value = "原id"),
            @ApiImplicitParam(name = "relId", value = "变动后相对变化的id"),
            @ApiImplicitParam(name = "type", value = "变化 类型 before  after  inner"),
    })
    @RequestMapping(value = "/updateSort", method = RequestMethod.POST)
    public Result updateSort(Long originId, Long relId, String type) {
        if (ParamsUtils.isInputEmpty(originId, relId, type)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        Dict originType = service.getOne(originId);
        Dict relType = service.getOne(relId);

        if (originType == null || relType == null) {
            return R.fail("操作失败");
        }
        if ("before".equals(type) || "after".equals(type)) {
            originType.setLevel(relType.getLevel());
            originType.setParent(relType.getParent());
//            //设置排序位置
            originType.setSort(relType.getSort());
            //查询同等级下相同类型的分类列表进行一次排序
            HashMap hashMap = new HashMap();
            hashMap.put("level", relType.getLevel());
            if (relType.getParent() != null)
                hashMap.put("parent.id", relType.getParent().getId());

            PageableRequest pageableRequest = new PageableRequest();
            pageableRequest.setSort(SortUtils.addSort(new Sort("sort", "asc")));
            List<Dict> list = service.queryToList(hashMap, pageableRequest);

            //先移除
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId() == originType.getId()) {
                    list.remove(i--);
                }
            }

            int relIndex = 0;
            for (int i = 0; i < list.size(); i++) {
//                if (relType.getSort() == list.get(i).getSort()) {
//                    list.get(i).setSort(i);
//                }
                if (relType.getId() == list.get(i).getId()) {
                    relIndex = i;
                }
            }

            if ("before".equals(type)) {
                list.add(relIndex, originType);
            } else if ("after".equals(type)) {
                list.add(relIndex + 1, originType);
            }

            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSort(i);
            }

            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).getName() + "   " + list.get(i).getSort());
            }
            service.save(list);
            service.save(originType);
        } else if ("inner".equals(type)) {
            originType.setLevel(relType.getLevel() + 1);
            originType.setParent(relType);
//            //设置排序位置
            originType.setSort(relType.getSort());
            //查询同等级下相同类型的分类列表进行一次排序
            HashMap hashMap = new HashMap();
            hashMap.put("level", relType.getLevel() + 1);
            if (relType.getParent() != null)
                hashMap.put("parent.id", relType.getId());

            PageableRequest pageableRequest = new PageableRequest();
            pageableRequest.setSort(SortUtils.addSort(new Sort("sort", "asc")));
            List<Dict> list = service.queryToList(hashMap, pageableRequest);

            //先移除
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId() == originType.getId()) {
                    list.remove(i--);
                }
            }

            list.add(originType);

            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSort(i);
            }

            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).getName() + "   " + list.get(i).getSort());
            }
            service.save(list);
            service.save(originType);
        }


//        Dict entity = originType.getParent();
//        if (entity != null) {//1级分类无需处理子分类的节点数据
//            //存储完后分析一次所有受影响的节点路劲再重新存储一次
//            entity.setNodePath(service.getNodePath(entity, ""));
//            service.sortType(entity);
//            service.setChildNodePath(entity.getChildren());
//            service.sortChildNodePath(entity.getChildren());
//            entity.setLevel(service.getTypeLevel(entity));
//        }

        return R.ok();
    }
}
